<template>
  <div>
    <el-table-form ref="form" :model="query">
      <el-form-item label="单号" prop="fillCode">
        <el-input
          v-model.trim="query.fillCode"
          placeholder="请输入"
          clearable
          @keyup.enter.native="search"
        />
      </el-form-item>
      <el-form-item label="仓库名称:" prop="storeId">
        <el-select v-model="query.storeId" clearable placeholder="请选择">
          <el-option
            v-for="item in storeMap"
            :key="item.storeId"
            :label="item.storeName"
            :value="item.storeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="billStatus">
        <el-select
          v-model="query.billStatus"
          filterable
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in billStatusMap"
            :key="item.value"
            :value="item.value"
            :label="item.desc"
          />
        </el-select>
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 150px; margin-right: 2px;">
          <el-option value="createTime" label="创建时间" />
          <el-option value="auditDt" label="审核时间" />
        </el-select>
        <el-date-picker
          v-model="queryDate"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <template v-slot:btns>
        <el-button
          v-permission="[70407, 1]"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;">
      <div>
        <el-button v-permission="[70407, 2]" type="primary" icon="el-icon-plus" @click="add">新增</el-button>
        <!-- <el-button
          v-permission="[70701, 2]"
          type="primary"
          icon="el-icon-download"
          @click="exportFile"
        >导出</el-button> -->
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      height="250"
      highlight-current-row
      element-loading-text="加载中"
      :column="columns"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <PlannedFillingOrderAdd ref="plannedFillingOrderAdd" :store-map="storeMap" />
    <PlannedFillingOrderAudit ref="plannedFillingOrderAudit" />
    <PlannedFillingOrderDetail ref="plannedFillingOrderDetail" :bill-status-map="billStatusMap" />
  </div>
</template>

<script>
  import dayjs from 'dayjs'
  import {
    queryMap,
    selectOrgSNNoAndReType,
    plannedFillingOrderQuery,
    cylinderRecoveryExport,
    queryExportDomain,
    plannedFillingOrderCancel
  } from '@/api'
  import { formatColumnMap } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import PlannedFillingOrderAdd from './components/Add'
  import PlannedFillingOrderAudit from './components/Audit'
  import PlannedFillingOrderDetail from './components/Detail'

  export default {
    name: 'plannedFillingOrder', // 计划充装单
    components: {
      PlannedFillingOrderAdd,
      PlannedFillingOrderAudit,
      PlannedFillingOrderDetail
    },
    data() {
      return {
        exportDomain: '', // 导出域名
        actionColWidth: 80,
        searchParams: {},
        query: {
          fillCode: '',
          storeId: '',
          billStatus: ''
        },
        queryDate: [],
        treeData: [],
        tableData: {
          total: 0,
          data: []
        },
        storeMap: [],
        billStatusMap: [], // 气瓶状态
        dateType: 'createTime'
      }
    },
    computed: {
      columns: function() {
        return [
          {
            prop: 'fillCode',
            minWidth: 160,
            label: '单号',
            render: (h, { row }) => (
            <el-link
              underline={false}
              onClick={() => this.openFillingOrderDetail(row)}
            >
              {row.fillCode}
            </el-link>
          )
          },
          {
            prop: 'storeName',
            label: '仓库名称',
            minWidth: 160
          },
          {
            prop: 'gdCount',
            label: '数量'
          },
          {
            prop: 'createUser',
            label: '创建人'
          },
          {
            prop: 'createTime',
            label: '创建时间',
            minWidth: 180,
            render: (h, { row }) => (
              <span>
              {row.createTime &&
                dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')}
              </span>
            )
          },
          {
            prop: 'auditor',
            label: '审核人'
          },
          {
            prop: 'auditDt',
            label: '审核时间',
            minWidth: 180,
            render: (h, { row }) => (
              <span>
              {row.auditDt &&
                dayjs(row.auditDt).format('YYYY-MM-DD HH:mm:ss')}
              </span>
            )
          },
          {
            prop: 'billStatus',
            label: '状态',
            render: (h, { row }) => (
              <span>
                {row.billStatus
                  ? formatColumnMap(
                      this.billStatusMap,
                      'value',
                      row.billStatus,
                      'desc'
                    )
                  : ''}
              </span>
            )
          },
          {
            label: '操作',
            width: '80px',
            fixed: 'right',
            render: (h, { row }, $index) => {
              return (
              <div>
                {row.billStatus === 1 && (
                  <el-link
                    v-show={this.$btnPermission([70407, 4])}
                    type='danger'
                    underline={false}
                    size='mini'
                    onClick={() => this.handleCancel(row)}
                  >
                    作废
                  </el-link>
                )}
                {row.billStatus === 1 && row.isScan !== 2 && (
                  <el-link
                    v-show={this.$btnPermission([70407, 3])}
                    underline={false}
                    size='mini'
                    onClick={() => this.handleAudit(row)}
                  >
                    审核
                  </el-link>
                )}
              </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await Promise.all([this.queryOptionsMap(), this.getStoreMap(), this.getExportDomain()])
    },
    methods: {
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain).then(res => {
          this.exportDomain = res.data
        })
      },
      // 查询枚举 客户类型
      async queryOptionsMap() {
        const [res1] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'FillBillStatus' })
        ])
        this.billStatusMap = res1.data
      },
      async getStoreMap() {
        const res = await selectOrgSNNoAndReType({
          currentPage: 1,
          pageSize: 9999,
          reType: 3
        })
        this.storeMap = res.data
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      refresh() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async fetchData({ currentPage = 1, pageSize = 20 }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.queryDate && this.queryDate.length > 0) {
          query[this.dateType] = this.queryDate[0]
          query[this.dateType + 'End'] = this.queryDate[1]
        }
        const res = await plannedFillingOrderQuery(query)
        this.searchParams = query
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom =
                actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.columns))
          copyColumn.pop() // 删除操作列
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          cylinderRecoveryExport({
            // paramInfo: _this._getQuery(_this.searchParams),
            paramInfo: _this.searchParams,
            kv: str // 表格列
          }).then(res => {
            window.open(
              `${_this.exportDomain}/page/export/frame?key=${res.data}`,
              '_blank'
            )
          })
        })
      },
      async openFillingOrderDetail(row) {
        await this.$refs.plannedFillingOrderDetail.open(row)
      },
      handleCancel(row) {
        this.$confirm('确认要作废该计划充装单记录？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            const res = await plannedFillingOrderCancel({ fillCode: row.fillCode })
            if (res) {
              this.$message.success('操作成功！')
              this.search()
            }
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            })
          })
      },
      async add() {
        await this.$refs.plannedFillingOrderAdd.open()
        this.search()
      },
      async handleAudit(row) {
        await this.$refs.plannedFillingOrderAudit.open(row)
        this.search()
      }
    }
  }
</script>

<style lang="scss" scoped></style>
